// 文件路径: src/main/java/com/macro/mall/tiny/modules/oms/controller/CartController.java
package com.macro.mall.tiny.modules.oms.controller;

import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.modules.oms.dto.CartChangeSkuParam;
import com.macro.mall.tiny.modules.oms.dto.CartListQueryParam;
import com.macro.mall.tiny.modules.oms.dto.CartParam;
import com.macro.mall.tiny.modules.oms.dto.CartUpdateParam;
import com.macro.mall.tiny.modules.oms.model.Cart;
import com.macro.mall.tiny.modules.oms.service.CartService;
import com.macro.mall.tiny.modules.oms.vo.CartItemVO;
import com.macro.mall.tiny.modules.pms.service.ProductSkuService;
import com.macro.mall.tiny.security.util.JwtTokenUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.macro.mall.tiny.common.api.CommonPage;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * <p>
 * 购物车表 前端控制器
 * </p>
 *
 * @author macro
 * @since 2023-11-07
 */
@Controller
@Tag(name = "CartController", description = "购物车管理")
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private CartService cartService;

    @Operation(summary = "获取用户购物车列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<Cart>> list(@RequestParam(required = false) Integer userId,
                                         @RequestParam(required = false) String token) {
        // 如果没有直接提供userId，尝试从token中解析
        if (userId == null && token != null) {
            try {
                String userIdStr = jwtTokenUtil.getUserNameFromToken(token);
                if (userIdStr != null && !userIdStr.isEmpty()) {
                    userId = Integer.parseInt(userIdStr);
                }
            } catch (Exception e) {
                return CommonResult.failed("无效的token");
            }
        }
        
        // 确保userId已提供且有效
        if (userId == null) {
            return CommonResult.failed("用户ID不能为空");
        }
        
        List<Cart> cartList = cartService.list(userId);
        return CommonResult.success(cartList);
    }

    @Autowired
    private ProductSkuService productSkuService;

    // 修改 CartController 类中的分页查询接口
    @Operation(summary = "分页获取用户购物车列表（包含商品信息）")
    @RequestMapping(value = "/pageListWithProductInfo", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<CartItemVO>> pageListWithProductInfo(CartListQueryParam queryParam) {
        // 从token中解析用户ID，如果queryParam中没有提供userId
        if (queryParam.getUserId() == null && queryParam.getToken() != null) {
            try {
                String userIdStr = jwtTokenUtil.getUserNameFromToken(queryParam.getToken());
                if (userIdStr != null && !userIdStr.isEmpty()) {
                    queryParam.setUserId(Integer.parseInt(userIdStr));
                }
            } catch (Exception e) {
                return CommonResult.failed("无效的token");
            }
        }

        Page<CartItemVO> cartItemPage = cartService.pageListWithProductInfo(queryParam);
        return CommonResult.success(CommonPage.restPage(cartItemPage));
    }

    @Operation(summary = "添加商品到购物车")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult addToCart(@Validated @RequestBody CartParam cartParam) {

        // 从token中解析用户ID，如果queryParam中没有提供userId
        if (cartParam.getUserId() == null && cartParam.getToken() != null) {
            try {
                String userIdStr = jwtTokenUtil.getUserNameFromToken(cartParam.getToken());
                if (userIdStr != null && !userIdStr.isEmpty()) {
                    cartParam.setUserId(Integer.parseInt(userIdStr));
                }
            } catch (Exception e) {
                return CommonResult.failed("无效的token");
            }
        }

        // 确保userId已提供且有效
        if (cartParam.getUserId() == null) {
            return CommonResult.failed("用户ID不能为空");
        }

        Integer cartId = cartService.addToCart(cartParam);
        if (cartId != null) {
            Map<String, Object> data = new HashMap<>();
            data.put("cartId", cartId);
            return CommonResult.success(data, "添加成功");
        } else {
            return CommonResult.failed("添加失败");
        }
    }

    @Operation(summary = "更新购物车商品数量和备注")
    @RequestMapping(value = "/update/{cartId}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateCart(@PathVariable Integer cartId,
                                   @Validated @RequestBody CartUpdateParam updateParam) {
        boolean success = cartService.updateCart(cartId, updateParam);
        if (success) {
            return CommonResult.success(null, "更新成功");
        } else {
            return CommonResult.failed("更新失败");
        }
    }

    @Operation(summary = "从购物车删除商品")
    @RequestMapping(value = "/delete/{cartId}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult deleteFromCart(@PathVariable Integer cartId) {
        boolean success = cartService.deleteFromCart(cartId);
        if (success) {
            return CommonResult.success(null, "删除成功");
        } else {
            return CommonResult.failed("删除失败");
        }
    }

    @Operation(summary = "更换购物车中的SKU")
    @RequestMapping(value = "/changeSku", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult changeSku(@Validated @RequestBody CartChangeSkuParam changeSkuParam) {
        boolean success = cartService.changeSku(changeSkuParam);
        if (success) {
            return CommonResult.success(null, "更换成功");
        } else {
            return CommonResult.failed("更换失败");
        }
    }

    @Operation(summary = "批量删除购物车项")
    @RequestMapping(value = "/delete/batch", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult deleteBatch(@RequestBody List<Integer> cartIds) {
        boolean success = cartService.deleteBatch(cartIds);
        if (success) {
            return CommonResult.success(null, "批量删除成功");
        } else {
            return CommonResult.failed("批量删除失败");
        }
    }
}